package com.xiaoyu.aop.framework;

import com.xiaoyu.aop.AdvisedSupport;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {
    private final AdvisedSupport advise;

    public JdkDynamicAopProxy(AdvisedSupport advisedSupport) {
        this.advise = advisedSupport;
    }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(getClass().getClassLoader(), advise.getTargetSource().getTargetClass(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (advise.getMethodMatcher().matches(method, advise.getTargetSource().getTarget().getClass())) {
            MethodInterceptor methodInterceptor = advise.getMethodInterceptor();
            return methodInterceptor.invoke(new ReflectiveMethodInvocation(advise.getTargetSource().getTarget(), method, args));
        }
        return method.invoke(advise.getTargetSource().getTarget(), args);
    }
}
